package webtest

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	contextmodel "go-caipu/pkg/services/contexthandler/model"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

type Server struct {
	t          testing.TB
	engine     *gin.Engine
	TestServer *httptest.Server
}

func NewServer(t testing.TB, engine *gin.Engine) *Server {
	t.Helper()
	//m := gin.New()
	//m.Handlers = append(m.Handlers, router) //添加路由
	testServer := httptest.NewServer(engine.Handler())
	t.Cleanup(testServer.Close)
	return &Server{
		t:          t,
		engine:     engine,
		TestServer: testServer,
	}
}
func (s *Server) NewRequest(method string, target string, body io.Reader) *http.Request {
	s.t.Helper()

	if !strings.HasPrefix(target, "/") {
		target = "/" + target
	}
	target = s.TestServer.URL + target
	req := httptest.NewRequest(method, target, body)
	reqID := generateRequestIdentifier()
	req = requestWithRequestIdentifier(req, reqID)
	req.RequestURI = ""
	return req

}

func (s *Server) NewGetRequest(target string) *http.Request {
	return s.NewRequest(http.MethodGet, target, nil)
}
func (s *Server) NewPostRequest(target string, body io.Reader) *http.Request {
	return s.NewRequest(http.MethodPost, target, body)
}
func (s *Server) Send(req *http.Request) (*http.Response, error) {
	return http.DefaultClient.Do(req)
}
func (s *Server) SendJSON(req *http.Request) (*http.Response, error) {
	req.Header.Add("Content-Type", "application/json")
	return s.Send(req)
}
func generateRequestIdentifier() string {
	return uuid.NewString()
}
func requestWithRequestIdentifier(req *http.Request, id string) *http.Request {
	req.Header.Set("X-GRAFANA-WEB-TEST-ID", id)
	return req
}
func requestIdentifierFromRequest(req *http.Request) string {
	return req.Header.Get("X-GRAFANA-WEB-TEST-ID")
}

var requests = map[string]*contextmodel.ReqContext{}

func RequestWithWebContext(req *http.Request, c *contextmodel.ReqContext) *http.Request {
	reqID := requestIdentifierFromRequest(req)
	requests[reqID] = c
	return req

}
func requestContextFromRequest(req *http.Request) *contextmodel.ReqContext {
	reqID := requestIdentifierFromRequest(req)
	val, exists := requests[reqID]
	if !exists {
		return nil
	}

	return val
}
